﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using EDTS.Model.Weixin;
using EDTS.Logic.Weixin;
using EDTS.Weixin.Submits;
using Newtonsoft.Json.Linq;
namespace EDTS.WinServices
{
    public class SendMessage:Task
    {
        public SendMessage(ISchedule schedule) : base(schedule) { }

        public override void Execute(object param)
        {
            base.Execute(param);
            JObject ret = null;
            while (Common.Power)
            {
                try
                {
                    var lst = WxMessageLogic.GetWaiting(100);
                    if (lst.TotalRecordsCount > 0)
                    {
                        foreach (var msg in lst)
                        {
                            try
                            {
                                var token = WxAppLogic.GetAccessToken(msg.AppGuid);
                                switch (msg.MsgType)
                                {
                                    case "News":
                                        ret = Messages.SendNews(token, msg.Receiver, msg.Description);
                                        break;
                                    default:
                                        ret = Messages.SendText(token, msg.Receiver, msg.Description, msg.Safe);
                                        break;
                                }
                                var retmsg=Newtonsoft.Json.JsonConvert.SerializeObject(ret);
                                WxMessageLogic.SetResult(msg.ID, WxMessageStatus.Success, retmsg);
                            }
                            catch (Exception ex)
                            {
                                WxMessageLogic.SetResult(msg.ID, WxMessageStatus.Failed, null, ex.Message);
                            }
                        }
                    }
                    else
                        Thread.Sleep(5000);
                }
                catch (Exception ex)
                {
                    Utils.LogHelper.SaveErrorLog(ex, Common.ErrPath);
                }
            }
        }
    }
}
